package main

import (
	"context"
	"fmt"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"sale_system/inventory_srv/proto"
	"sync"
)

var client proto.InventoryClient
var conn *grpc.ClientConn

func Init() {
	var err error

	conn, err = grpc.Dial("192.168.56.103:8899", grpc.WithInsecure())
	if err != nil {
		panic("failed to connect, " + err.Error())
	}

	client = proto.NewInventoryClient(conn)
}

func TestSetInv() {

	_, _ = client.SetInv(context.Background(), &proto.GoodsInvInfo{
		GoodsId: 421,
		Num:     991,
	})
	_, _ = client.SetInv(context.Background(), &proto.GoodsInvInfo{
		GoodsId: 422,
		Num:     30,
	})
}

func TestInvDetail() {

	rsp, _ := client.InvDetail(context.Background(), &proto.GoodsInvInfo{
		GoodsId: 421,
	})

	fmt.Println(rsp)
}

func TestSell(wg *sync.WaitGroup) {

	defer wg.Done()
	GoodsInfos := make([]*proto.GoodsInvInfo, 0)
	GoodsInfos = append(GoodsInfos, &proto.GoodsInvInfo{
		GoodsId: 421,
		Num:     1,
	})
	_, err := client.Sell(context.Background(), &proto.SellInfo{
		GoodsInfo: GoodsInfos,
	})
	if err != nil {
		zap.S().Infof("库存扣减失败！！！%s", err)
	}
}

func TestReBack() {
	GoodsInfos := make([]*proto.GoodsInvInfo, 0)
	GoodsInfos = append(GoodsInfos, &proto.GoodsInvInfo{
		GoodsId: 421,
		Num:     10,
	})

	_, _ = client.ReBack(context.Background(), &proto.SellInfo{
		GoodsInfo: GoodsInfos,
	})
}

func main() {

	Init()
	defer conn.Close()

	wg := &sync.WaitGroup{}
	wg.Add(30)
	for i := 0; i < 30; i++ {
		go TestSell(wg)
	}

	wg.Wait()
}
